import { editLockOper } from '../apis/req';
import base from './base';
import { doSave_nNew } from './rightBtn';
import { closeRequestPage,reloadRequestPage } from './formUtil';
import { getAntd,getEcCom,getLabel } from './convert';

//加载绑定相关事件
export const bindLockEvent = () =>{
    // if (window.addEventListener){
    //     window.addEventListener("unload", closeUnLock, false);
    // }else if (window.attachEvent){
    //     window.attachEvent("onunload", closeUnLock);
    // }else{
    //     window.onuload = closeUnLock;
    // }
}

//判断当前请求是否开启锁定
export const judgeOpenLock = () =>{
    const { promptInfo } = base.globalStore;
    return promptInfo && promptInfo.prompttype === "editlock";
}

//手动点击解锁
export const doUnLock = () =>{
    const { Modal,message } = getAntd();
    const { commonParam } = base.globalStore;
    if(commonParam.belongTest){
        message.warning(getLabel(386177,"流程测试不允许解除锁定操作"));
        return;
    }
    Modal.confirm({
        title: getLabel(131329,'信息确认'),
        content: getLabel(128824,'是否保存当前流程数据？'),
        okText: getLabel(83446,'确定'),
        cancelText: getLabel(31129,'取消'),
        onOk: ()=>{
            closeUnLock(()=>{
                doSave_nNew(true);
            })
        },
        onCancel: ()=>{
            closeRequestPage(false);
        }
    });
}

//手动点击激活当前页面，失效已打开同请求页面
export const doActivate = () =>{
    editLockOper(getLockParams("doActivate")).then(data =>{
        const { urlParams } = base.globalStore;
        delete urlParams["timestamp"];
        reloadRequestPage(urlParams, false);
    });
}

//校验当前页面是否有效
export const verifyEffictive = (callback) =>{
    if(!judgeOpenLock())
        return;
    editLockOper(getLockParams("verifyEffictive")).then(data =>{
        typeof callback === "function" && data.flag == "true" && callback();
    });
}

//关闭页面解锁此流程
export const closeUnLock = (callback) =>{
    if(!judgeOpenLock())
        return;
    editLockOper(getLockParams("unlock")).then(data =>{
        typeof callback === "function" && callback();
    });
}

export const getLockParams = (opertype) =>{
    const { urlParams,baseParam } = base.globalStore;
    return {...{opertype}, ...urlParams, ...baseParam};
}

window.lockUtil = {
    doUnLock: doUnLock,
    doActivate: doActivate,
}
